package com.huitone.smspfm.task;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import com.huitone.smspfm.logger.ExtLogger;

import com.huitone.smspfm.core.config.AppStaticConfigs;

/**   
* @Title: ForbidSmsProcessingManager.java 
* @Package com.huitone.smspfm.module 
* @Description: TODO(用一句话描述该文件做什么) 
* @author ybliang   
* @date 2017年3月15日 下午3:52:00 
* @version V1.0   
*/
public class SMAffixZsetTask extends Thread {

	private static ExtLogger logger = ExtLogger.create(SMAffixZsetTask.class);
	
	private ExecutorService blockingPool = new ThreadPoolExecutor(5, 
			5, 1L, TimeUnit.MINUTES, new ArrayBlockingQueue<>(10), new RejectedExecutionHandler() {
		
		@Override
		public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
			boolean offer = false;
			while(!executor.isShutdown() && !offer) {
				offer = executor.getQueue().offer(r);
				if (!offer) {
					try {
						TimeUnit.MILLISECONDS.sleep(100);
					} catch (InterruptedException e) {}
				}
			}
		}
	});
	
	private long excuteInterval = 60000;
	
	private boolean keepGoing = true;
	
	@Override
	public void run() {
		
		while(isKeepGoing() && !this.isInterrupted()) {
			
			blockingPool.execute(new Runnable() {
				
				@Override
				public void run() {
					
					try {
						
						AppStaticConfigs.zsetOpts2.removeByScore(AppStaticConfigs.iSMAffixZSet, 0, System.currentTimeMillis());
						
					} catch (Exception e) {
						logger.error(e.getMessage());
					}
				}
			});
			
			try {
				Thread.sleep(excuteInterval);
			} catch (InterruptedException e) {}
		}
		
		if (blockingPool != null && !blockingPool.isShutdown()) {
			blockingPool.shutdown();
		}
		
	}
	
	public boolean isKeepGoing() {
		return keepGoing;
	}

	public void setKeepGoing(boolean keepGoing) {
		this.keepGoing = keepGoing;
	}

	@Override
	public void destroy() {
		this.setKeepGoing(false);
		this.interrupt();
	}
}
